import { VIP_PAY_BASE_URL } from '@/config/runtime'

/**
 * 通过创建隐藏表单的方式发起 VIP 支付。
 * 由于后端返回 302 重定向，使用 form.submit 可以自动跟随并跳转支付宝支付页。
 * @param {Object} options
 * @param {string|number} options.amount - 支付金额，单位元
 * @param {string} options.subject - 订单标题
 * @param {string} [options.target='_blank'] - 打开支付页的目标窗口
 */
export function openVipPayment({ amount, subject, target = '_blank' }) {
  if (typeof window === 'undefined') {
    throw new Error('只能在浏览器环境下发起支付')
  }
  if (!amount) {
    throw new Error('缺少支付金额')
  }
  if (!subject) {
    throw new Error('缺少订单标题')
  }

  const params = new URLSearchParams()
  params.set('amount', amount)
  params.set('subject', subject)
  const payUrl = `${VIP_PAY_BASE_URL}/create_pay?${params.toString()}`

  const windowName = target === '_blank' ? `vipPay_${Date.now()}` : target
  let payWindow = null
  try {
    payWindow = window.open(payUrl, windowName, 'noopener=yes')
  } catch (error) {
    payWindow = null
  }

  if (!payWindow || payWindow.closed || payWindow.location.href === 'about:blank') {
    window.location.href = payUrl
    return Promise.resolve({ window: null, fallbackToSelf: true })
  }

  return Promise.resolve({ window: payWindow, fallbackToSelf: false })
}

/**
 * 获取订单详情（仅限演示环境使用）
 * @param {string} outTradeNo
 */
export async function fetchVipOrder(outTradeNo) {
  if (!outTradeNo) {
    throw new Error('缺少订单编号')
  }

  const response = await fetch(`${VIP_PAY_BASE_URL}/orders/${outTradeNo}`, {
    credentials: 'include',
  })

  if (!response.ok) {
    throw new Error('获取订单信息失败')
  }

  return response.json()
}

/**
 * 获取调用支付宝查询接口所需的签名字符串
 * @param {string} outTradeNo
 */
export async function createGatewayQuery(outTradeNo) {
  if (!outTradeNo) {
    throw new Error('缺少订单编号')
  }

  const response = await fetch(`${VIP_PAY_BASE_URL}/alipay/query/${outTradeNo}`, {
    credentials: 'include',
  })

  if (!response.ok) {
    throw new Error('查询支付宝网关失败')
  }

  return response.json()
}

